package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.config.LocalUserId;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.SpecialAreaDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.CompletableFuture;

/**
 * 特殊区域代理
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2023-08-29 11:28:52
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class SpecialAreaService{

  private final SpecialAreaDao specialAreaDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public SpecialAreaService(final SpecialAreaDao specialAreaDao,final ThreadPoolTaskExecutor taskExecutor){
    this.specialAreaDao = specialAreaDao;
    this.taskExecutor = taskExecutor;
  }

  public String listAreaProxy(){
    final String loginId = LocalUserId.get();
    return CompletableFuture.supplyAsync(()->{
      try{
        final long loginKey = Long.parseLong(loginId);
        final boolean is_super = ConfigFile.manager(loginKey);
        if(is_super){
          //管理员要显示全部
          return ToolClient.queryJson(specialAreaDao.getAllAreaProxy());//管理员查看
        }
        final HashMap<String,Object> proxyType = specialAreaDao.getAreaProxyType(loginKey);
        if(proxyType == null){
          return ToolClient.createJsonFail("您不是代理商");
        }
        final Long areaId = (Long)proxyType.get("area_id");
        if(areaId == null){
          return ToolClient.createJsonFail("暂无权限查看");
        }
        //其实应该是不存在省级代理查看的场景,所以仅需处理type = 2 ; type = 3 即可
        final PageFormData formData = new PageFormData();
        final Integer type = (Integer)proxyType.get("type");
        formData.put("loginId",loginKey);
        switch (type){
          case 1://省代,可查看type = 2,3
            return ToolClient.queryJson(specialAreaDao.listAreaProxy(formData));
          case 2://市代,仅查询区代即可
            formData.put("type",type);
            return ToolClient.queryJson(specialAreaDao.listAreaProxy(formData));
          case 3://区代,仅有门店,仅显示门店
            return ToolClient.json198(loginId);
          default:
            return ToolClient.jsonValidateField();
        }
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }

  public String listAreaShop(final String userId){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(userId == null || userId.length() == 0){
          return ToolClient.jsonValidateField();
        }
        return ToolClient.queryJson(specialAreaDao.listAreaShop(Long.parseLong(userId)));
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}